package com.botann.projects.filter;

import com.botann.projects.service.AdminUserServiceIntf;
import com.botann.projects.utils.TokenUtils;
import com.botann.projects.service.AdminUserServiceIntf;
import com.botann.projects.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Charging
 * LoginInterceptor
 * Created by 刘山国 on 2017/11/27.
 * Copyright (c) 2017 刘山国. All rights reserved
 */
public class LoginInterceptor extends BaseInterceptor {

    @Override
    public Class loggerClass() {
        return LoginInterceptor.class;
    }

    @Autowired
    protected AdminUserServiceIntf service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 测试框架请求,直接放行
        if (request.getAttribute("testKey") != null) {
            String uri = request.getRequestURI();
            String url = uri == null ? "" : uri;
            System.out.println("测试请求访问->>-- " + url);
            return true;
        }
        // 未登录||，已登录但是token验证失败 ==就跳转未登录提示接口
        if (!loginCheck(request,response)) {//验证不通过
            forward(request,response,"/unauthorized");
//            response.sendRedirect(request.getContextPath() + API.URL_UNAUTHORIZED);
            return false;
        }
        return true;
    }

    private boolean loginCheck(HttpServletRequest request,HttpServletResponse response) {

        // 0. 请求url 在token验证前处理
        String url = getResolvdeUrl(request);
//        logger.info(url);
        // token 记录
        String authToken = extractAuthTokenFromRequest(request);
        logger.info("--token验证->> ");
        logger.info(authToken);

        Object info = TokenUtils.checkSign(authToken,service,request,response);
        boolean success = !(info instanceof String);

        if (success) {
            logger.info("token验证通过");
        } else {
            logger.info(info);
        }

        // 记录请求日志
        generateRequestLog(request,success ? (Integer) info:0,success,success?"正常 ":"token验证失败 " + info);

        return success;
    }




}
